import 'package:HnXG/Api.dart';
import 'package:HnXG/DIalog.dart';
import 'package:HnXG/Request/Request3.dart';
import 'package:HnXG/Request/Request7.dart';
import 'package:HnXG/Request/TaskAgvRequest.dart';
import 'package:HnXG/snackbar.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../tools/keepAliveWrapper.dart';

class NewWarehousePage extends StatefulWidget {
  const NewWarehousePage({super.key});

  @override
  State<StatefulWidget> createState() => _NewWarehousePage();

  
}

class _NewWarehousePage extends State<NewWarehousePage> with SingleTickerProviderStateMixin {
  // 搜索框控制器，用于获取输入内容
  final TextEditingController _searchController = TextEditingController();
  // 存储仓库占用状态的列表
  List<bool> warehouseOccupancy = List.filled(4, false);
  // 新增物料信息变量，初始值为 null
  String? materialInfo;

  @override
  void initState() {
    super.initState();
    fetchWarehouseStatus();
  }
  //焦点
final FocusNode _focusNode = FocusNode();
  // 异步方法，通过 Api 类的 GetView_PositionState 接口获取仓库状态
  Future<void> fetchWarehouseStatus() async {
    try {
      final response = await Api.GetView_PositionState(Request3(Type: "仓库"));
      print(response['dto']);
      if (response!= null && response['dto'] != null) {
        setState(() {
          for (int i = 0; i < 4; i++) {
            warehouseOccupancy[i] = response['dto'][i]['isOccupy'];
          }
        });
      }
    } catch (e) {
      print('获取仓库状态时出错: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('新仓入库',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            shadows: [Shadow(color: Colors.black38, offset: Offset(1,1), blurRadius: 3)],
          )
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.blue.shade700, Colors.lightBlue.shade400],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
          ),
        ),
        centerTitle: true,
        elevation: 4,
        automaticallyImplyLeading: false,
      ),
  
        // 隐藏返回图标
      body: Padding(
        padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
        child: SingleChildScrollView(  // 可滚动容器，防止键盘弹出时布局溢出
          physics: AlwaysScrollableScrollPhysics(),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 物料搜索区域
              _buildSearchSection(context),
              const SizedBox(height: 20),
              // 产线1入库按钮区域
              _buildProductionLineSection('入库', _buildLine1Buttons()),
              const SizedBox(height: 20),
              // 产线2入库按钮区域
              _buildProductionLineSection('入库', _buildLine2Buttons()),
              const SizedBox(height: 20),
              // 仓库空余状态展示区域
              // _buildWarehouseStatusSection(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建仓库空余状态展示区域
  Widget _buildWarehouseStatusSection() {




    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 区域标题
        const Text('仓库空余状态', style: TextStyle(fontWeight: FontWeight.bold)),
        const SizedBox(height: 8),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            for (int i = 0; i < 4; i++)
              _buildWarehouseStatusIndicator('仓库${i + 1}', warehouseOccupancy[i]),
          ],
        ),
      ],
    );
  }

  /// 构建单个仓库状态指示器
  Widget _buildWarehouseStatusIndicator(String name, bool isOccupied) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 1), // 增加水平间距
      width: 80, // 缩小宽度
      height: 40, // 缩小高度
      decoration: BoxDecoration(
        color: isOccupied ? Colors.red : Colors.green,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Center(
        child: Text(
          name,
          style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12), // 缩小字体
        ),
      ),
    );
  }

  /// 构建搜索区域组件
  Widget _buildSearchSection(BuildContext contextGlobal) {
    return Column( 
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 区域标题
        const Text('物料搜索', style: TextStyle(fontWeight: FontWeight.bold)),
        const SizedBox(height: 8),
        // 搜索输入行
        Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 输入框（占满剩余空间）
            TextField(
              controller: _searchController,
              autofocus: false, // 自动获取焦点,
              focusNode:  _focusNode,
              onSubmitted: (value) async {
                final response = await Api.SearchMaterialList(Request7(MaterialList_Name: value));
                setState(() {
                  materialInfo = response['dto'];
                //我想在获取到数据后，清空输入框
                _searchController.clear();
                //我想在上一步执行结束后，将光标再移动到输入框
                _focusNode.requestFocus();
                
               
                });
              },
              decoration: InputDecoration(
                border: OutlineInputBorder(), // 边框样式
                hintText : '输入物料编号',         // 提示文字
                hintStyle: TextStyle(color: Colors.black, fontSize: 18), // 加大提示文字字体大小并设置为红色
              ),
              style: TextStyle(fontSize: 18), // 加大输入文字字体大小
            ),
            const SizedBox(height: 10),
            // 按钮行
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // 搜索按钮
                Expanded(
                  child: ElevatedButton.icon(
                    style: ElevatedButton.styleFrom(backgroundColor: Colors.blue),
                    onPressed: () async {
                    FocusScope.of(context).unfocus();
                    await Future.delayed(Duration(milliseconds: 100));
                    final response= await   Api.SearchMaterialList(Request7(MaterialList_Name: _searchController.text));
            
                     setState(() {
                       materialInfo=response['dto'];
                      
                     });

                   


                    }, // 点击事件待实现
                    icon: const Icon(Icons.search, color: Colors.white),
                    label: const Text('搜索', style: TextStyle(color: Colors.white)),
                  ),
                ),
                const SizedBox(width: 10),
                // 进库按钮
                Expanded(
                  child: ElevatedButton.icon(
                    style: ElevatedButton.styleFrom(backgroundColor: Colors.grey),
                    onPressed: () async {
                      FocusScope.of(context).unfocus();
                      await Future.delayed(Duration(milliseconds: 100));
                      final result = await InfoDialog.show(context, "提示信息", "您确定要进库吗")
                          .whenComplete(() => FocusScope.of(context).unfocus());
                      if (result == true) {
                                if( materialInfo==null){
                        ErrorSnackBar.show(context, message: "请先搜索物料");
                         return;
                       }else{
                      
  print(materialInfo);

                        if(materialInfo=="包装"){
                         final response=await Api.CreateTaskOrder(TaskAgvRequest(origination_Code: "Loc-8-1", target_Code: "Loc-2-1"));
                            if(response['state']==true){
                              print( " 回传 ${response['state']} ");
   SuccessSnackBar.show(context, message: response['msg']);
   }
   else{
    ErrorSnackBar.show(context, message: response['msg']);
   }
                        }
                           if(materialInfo=="非包装"){
                         final response=await Api.CreateTaskOrder(TaskAgvRequest(origination_Code: "Loc-8-1", target_Code: "Loc-3-1"));
                            if(response['state']==true){
   SuccessSnackBar.show(context, message: response['msg']);
   }
   else{
    ErrorSnackBar.show(context, message: response['msg']);
   }
                        }
                        else{
                           // ignore: use_build_context_synchronously
                           ErrorSnackBar.show(contextGlobal, message: "不存在的包装区");
                        }



                         }
                      }
               
                      }, // 点击事件待实现
                    icon: const Icon(Icons.inventory_2, color: Colors.white),
                    label: const Text('进库', style: TextStyle(color: Colors.white)),  
                  ),
                )
              ],
            )
          ],
        ),
        const SizedBox(height: 8),
        // 物料信息显示容器
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(16), // 增加内边距
          color: Colors.grey[200], // 浅灰色背景
          child: Text(
            materialInfo ?? "请输入物料编号",
            style: TextStyle(fontSize: 16,color: Colors.red)
          ),
        )
      ],
    );
  }

  /// 构建产线入库区域通用模板
  Widget _buildProductionLineSection(String title, Widget buttons) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 区域标题
        Text(title, style: TextStyle(fontWeight: FontWeight.bold)),
        const SizedBox(height: 8),
        // 按钮布局
        buttons,
      ],
    );
  }

  /// 构建产线1的仓库按钮组
  Widget _buildLine1Buttons() {
    return Wrap(
      spacing: 10,    // 水平间距
      runSpacing: 10, // 垂直间距
      children: [
        _buildWarehouseButton('完成品1——>非包装(仓库)',"Loc-8-1","Loc-2-1",context),
        _buildWarehouseButton('完成品1——>包装(仓库)',"Loc-8-1","Loc-3-1",context),
        // _buildWarehouseButton('产线1——>仓库3',"Loc-7-1","Loc-3-1",context),
        // _buildWarehouseButton('产线1——>仓库4',"Loc-7-1","Loc-4-1",context),
      ],
    );
  }

  /// 构建产线2的仓库按钮组
  Widget _buildLine2Buttons() {
    return Wrap(
      spacing: 10,
      runSpacing: 10,
      children: [
        _buildWarehouseButton('完成品2——>非包装(仓库)',"Loc-7-1","Loc-2-1",context),
        _buildWarehouseButton('完成品2——>包装(仓库)',"Loc-7-1","Loc-3-1",context),
        // _buildWarehouseButton('产线2——>仓库3',"Loc-8-1","Loc-3-1",context),
        // _buildWarehouseButton('产线2——>仓库4',"Loc-8-1","Loc-4-1",context),
      ],
    );
  }

  /// 通用仓库按钮构建方法
  Widget _buildWarehouseButton(String text,String origination_Code,String target_Code,BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.blue,   // 按钮背景色
        minimumSize: Size(120, 40),     // 最小尺寸
        shape: RoundedRectangleBorder(   // 圆角边框
          borderRadius: BorderRadius.circular(8)),
      ),
      onPressed: () async {
                FocusScope.of(context).unfocus();
                await Future.delayed(Duration(milliseconds: 100));
                final result = await InfoDialog.show(context, "提示信息", "您确定要下发任务吗？");
                if (result == true) {
                     final response=await Api.CreateTaskOrder(TaskAgvRequest(origination_Code: origination_Code, target_Code: target_Code));
   print(response);
   if(response['state']==true){
   SuccessSnackBar.show(context, message: response['msg']);
   }
   else{
    ErrorSnackBar.show(context, message: response['msg']);
   }
                }


      }, // 点击事件待实现
      child: Text(text, style: TextStyle(color: Colors.white)),
    );
  }

}